//
//  BDPayViewController.m
//  BadBoy
//
//  Created by wen on 2017/7/7.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPayViewController.h"
#import "BDShopCouponsModel.h"
#import "BDMallProductModel.h"
#import "BDHomeModel.h"
#import "BDMallProductPayTableViewCell.h"
#import "BDCouponPayTableViewCell.h"
#import "BDMalAddressTableViewCell.h"
#import "BDPayRedEnvelopeTableViewCell.h"
#import "BDPayDefaultTableViewCell.h"
#import "BDPayStyleTableViewCell.h"
#import "BDAddressChooseViewController.h"
#import "BDRedWhiteViewController.h"
#import "BDUserModel.h"
#import "BDUserAddressModel.h"
#import "BDAddressViewController.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "BDPayResultViewController.h"
#import "AppDelegate.h"
#import "BDRedEnvelopeModel.h"
#import "BDCityInfo.h"
#import "DNPayAlertView.h"
#import "BDForgetPasswordViewController.h"

typedef NS_ENUM(NSUInteger, BDPayViewControllerPayStyle) {
    BDPayViewControllerPayStyleBalance,
    BDPayViewControllerPayStyleZhifubao,
    BDPayViewControllerPayStyleWeixin
    
};

@interface BDPayViewController ()<UITableViewDelegate, UITableViewDataSource,UIAlertViewDelegate>{
    UIView *errorView;
    NSInteger errorCode;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, assign) BDPayViewControllerPayStyle payStyle;
@property (nonatomic, strong) BDUserAddressModel *address;
@property (nonatomic, strong) NSMutableArray *addressArray;
@property (nonatomic, strong) NSMutableArray *redEnvelopeArray;
@property (nonatomic, assign) NSInteger availableRedEnvelopeCount;
@property (nonatomic, strong) BDRedEnvelopeModel *currentRedEnvelope;
@property (nonatomic, copy) void (^successedBlock)();
@property (nonatomic, strong) NSString *notification;
@property (nonatomic, strong) NSDictionary *paraDic;
@property (nonatomic, strong) UIButton *payButton;
@end

@implementation BDPayViewController

- (instancetype)initWithPaySuccessedBlock:(void (^)())successedBlock{
    if (self = [super init]) {
        self.successedBlock = successedBlock;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"支付");
    self.payStyle = BDPayViewControllerPayStyleBalance;
    
    
    switch (self.payType) {
        case BDProductPayTypePost:{
            //需要红包，不需要地址
            RACSignal *signal = [RACSignal merge:@[[self getRedEnvelopeListWithType:BdRedEnvelopeTypePost]]];
            [signal subscribeCompleted:^{
                [self requestDatsource];
                [self.tableView reloadData];
            }];
        }break;
        case BDProductPayTypeProduct:{
            //需要地址，不需要红包
            RACSignal *signal = [RACSignal merge:@[[self getAddressList]]];
            [signal subscribeCompleted:^{
                [self requestDatsource];
                [self.tableView reloadData];
            }];
        }break;
        case BDProductPayTypeTransferToShop:{
            self.title = ASLocalizedString(@"选择支付方式");
            [self requestDatsource];
            [self.tableView reloadData];
        }break;
        case BDProductPayTypeCoupon:{
            //需要红包，不需要地址
            RACSignal *signal = [RACSignal merge:@[[self getRedEnvelopeListWithType:BdRedEnvelopeTypeMoney]]];
            [signal subscribeCompleted:^{
                [self requestDatsource];
                [self.tableView reloadData];
            }];
        }break;
        case BDProductPayTypeVIP:{
            [self requestDatsource];
            [self.tableView reloadData];
        }break;
        case BDProductPayTypeTopUp:{
            self.title = ASLocalizedString(@"充值");
            [self requestDatsource];
            [self.tableView reloadData];
        }break;
        default:
            break;
    }
}

- (void)requestDatsource{
    NSString *redString = @"";
    NSString *pricString = [NSString stringWithFormat:@"¥ %@", self.price];
    if (self.currentRedEnvelope != nil) {
        if (self.currentRedEnvelope.type == BdRedEnvelopeTypeMoney) {
            NSDecimalNumber *redDecimalNumber = [NSDecimalNumber decimalNumberWithString:self.currentRedEnvelope.money];
            NSDecimalNumber *curentDec = [self.price decimalNumberBySubtracting:redDecimalNumber];
            NSComparisonResult result = [curentDec compare:[NSDecimalNumber decimalNumberWithDecimal:[@(0) decimalValue]]];
            if (result < 0) {
                pricString = @"¥ 0.01";
            }else{
                pricString = [NSString stringWithFormat:@"¥ %@", curentDec];
            }
            redString = [NSString stringWithFormat:@"- ¥ %@", redDecimalNumber];

        }
    }
    
    switch (self.payType) {
        case BDProductPayTypePost:{
            if (self.currentRedEnvelope != nil) {
                NSString *redString = nil;
                if (self.availableRedEnvelopeCount == 0) {
                    redString = ASLocalizedString(@"无可用红包");
                }else{
                    redString = ASLocalizedString(@"主题红包");
                }
                self.datasource = @[@[@{@"identifier":@"mallProductPayCell", @"cellHeight":@"86", @"model":self.product}],
                                    @[@{@"identifier":@"redEnvelopeCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"红包"), @"placeholdTitle":[NSString stringWithFormat:ASLocalizedString(@"%@个红包可用"), @(self.availableRedEnvelopeCount)], @"subTitle":redString}}]].mutableCopy;
            }else {
                NSString *redString = nil;
                if (self.availableRedEnvelopeCount == 0) {
                    redString = ASLocalizedString(@"无可用红包");
                }else{
                    redString = @"";
                }
                self.datasource = @[@[@{@"identifier":@"mallProductPayCell", @"cellHeight":@"86", @"model":self.product}],
                                    @[@{@"identifier":@"redEnvelopeCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"红包"), @"placeholdTitle":[NSString stringWithFormat:ASLocalizedString(@"%@个红包可用"), @(self.availableRedEnvelopeCount)], @"subTitle":redString}},
                                      @{@"identifier":@"defaultCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"合计"), @"subTitle":pricString}}],
                                    @[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"余额"), @"image":@"yue", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleBalance)}},
                                      @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                      @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
            }
        }break;
        case BDProductPayTypeProduct:{
            self.datasource = @[@[@{@"identifier":@"mallProductPayCell", @"cellHeight":@"86", @"model":self.product}],
                                @[@{@"identifier":@"mallAddressCell", @"cellHeight":@"71", @"model":self.address == nil ? @"" : self.address},
                                  @{@"identifier":@"defaultCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"合计"), @"subTitle":pricString}}],
                                @[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"余额"), @"image":@"yue", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleBalance)}},
                                 @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
        }break;
        case BDProductPayTypeTransferToShop:{
            self.datasource = @[@[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"余额"), @"image":@"yue", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleBalance)}},@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
        }break;
        case BDProductPayTypeCoupon:{
            NSString *redString = nil;
            if (self.availableRedEnvelopeCount == 0) {
                redString = ASLocalizedString(@"无可用红包");
            }else{
                if (self.currentRedEnvelope == nil) {
                    redString = @"";
                }else{
                    redString = [NSString stringWithFormat:@"-¥ %@", [NSDecimalNumber decimalNumberWithString:self.currentRedEnvelope.money]];
                }
                
            }
            self.datasource = @[@[@{@"identifier":@"couponPayCell", @"cellHeight":@"159", @"model":self.product}],
                                @[@{@"identifier":@"redEnvelopeCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"红包"), @"placeholdTitle":[NSString stringWithFormat:ASLocalizedString(@"%@个红包可用"), @(self.availableRedEnvelopeCount)], @"subTitle":redString}},
                                  @{@"identifier":@"defaultCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"合计"), @"subTitle":pricString}}],
                                @[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"余额"), @"image":@"yue", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleBalance)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
        }break;
        case BDProductPayTypeVIP:{
            self.datasource = @[@[@{@"identifier":@"mallProductPayCell", @"cellHeight":@"86", @"model":self.product}],
                                @[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"余额"), @"image":@"yue", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleBalance)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
        }break;
        case BDProductPayTypeTopUp:{
            self.datasource = @[@[@{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"支付宝"), @"image":@"zfb_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleZhifubao)}},
                                  @{@"identifier":@"payStyleCell", @"cellHeight":@"45", @"model":@{@"title":ASLocalizedString(@"微信支付"), @"image":@"wx_icon", @"isChoose":@(self.payStyle == BDPayViewControllerPayStyleWeixin)}}]].mutableCopy;
        }break;
        default:
            break;
    }
}

- (RACSignal *)getAddressList{
    //1.获取地址列表
    NSString *url = [NSString stringWithFormat:@"%@user/address", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *addressSignal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [addressSignal subscribeNext:^(id  _Nullable x) {
        self.addressArray  = [BDUserAddressModel mj_objectArrayWithKeyValuesArray:x];
        if (self.addressArray.count == 0) {
            self.address = nil;
        }else{
            for (BDUserAddressModel *address in self.addressArray) {
                if (address.isDefault == YES) {
                    self.address = address;
                    break;
                }
            }
        }
        
    }];
    
    [addressSignal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
    return addressSignal;
}

- (RACSignal *)getRedEnvelopeListWithType:(BdRedEnvelopeType)type{
    NSString *url = [NSString stringWithFormat:@"%@hongBaos?page=1&size=50&type=%@&status=1", KBDBaseURL, @(type)];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *redEnvelopeSignal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [redEnvelopeSignal subscribeNext:^(id  _Nullable x) {
        self.redEnvelopeArray = [BDRedEnvelopeModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        if (type == BdRedEnvelopeTypePost) {
            self.availableRedEnvelopeCount = self.redEnvelopeArray.count;
        }else if (type == BdRedEnvelopeTypeMoney) {
            self.availableRedEnvelopeCount = 0;
            for (BDRedEnvelopeModel *redEnvelope in self.redEnvelopeArray) {
                //条件2：地区不合适
                BDShopCouponsModel *couponsModel = self.product;
                BOOL isEqualCityId = redEnvelope.agent_city_id == 0 || redEnvelope.agent_city_id == couponsModel.city_id;
                if (isEqualCityId == NO) {
                    //这里设置不合适的原因
                    BDCityInfo *cityInfo = [BDCityInfo getCityWithId:redEnvelope.agent_city_id];
                    redEnvelope.isEffective = NO;
                    redEnvelope.reason = [NSString stringWithFormat:ASLocalizedString(@"不可使用原因：该红包只能在%@使用"), cityInfo.name];
                }else{
                    //如果红包金额大于当前金额，红包不可用
                    NSComparisonResult result = [self.price compare:[NSDecimalNumber decimalNumberWithString:redEnvelope.money]];
                    if (result > 0) {
                        //否则判断红包限额是否小于当前金额
                        result = [self.price compare:[NSDecimalNumber decimalNumberWithString:redEnvelope.limit_money]];
                        if (result >= 0) {
                            self.availableRedEnvelopeCount++;
                            redEnvelope.isEffective = YES;
                        }else{
                            redEnvelope.isEffective = NO;
                            redEnvelope.reason = [NSString stringWithFormat:ASLocalizedString(@"不可使用原因：需满%@金额"), [NSDecimalNumber decimalNumberWithString:redEnvelope.limit_money]];
                        }
                    }else{
                        redEnvelope.isEffective = NO;
                        redEnvelope.reason = [NSString stringWithFormat:ASLocalizedString(@"不可使用原因：红包金额大于订单金额")];
                    }
                }
            }
        }
    }];
    [redEnvelopeSignal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
    return redEnvelopeSignal;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == _datasource.count - 1 && self.payType != BDProductPayTypePost) {
        return 35;
    }
    return 10;
}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    view.backgroundColor = [UIColor clearColor];
    if (section == _datasource.count - 1 && self.payType != BDProductPayTypePost) {
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        label.text = ASLocalizedString(@"选择支付方式");
        [label sizeToFit];
        label.left = 10;
        label.centerY = view.height / 2.0;
        [view addSubview:label];
    }else{
        for (UIView *subView in view.subviews) {
            [subView removeFromSuperview];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.datasource[indexPath.section][indexPath.row];
    return [dic[@"cellHeight"] floatValue];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.datasource[indexPath.section][indexPath.row];
    BDBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:dic[@"identifier"] forIndexPath:indexPath];
    if (indexPath.section == 0 && [self.shopTitle isNotEmpty]) {
        [(BDCouponPayTableViewCell *)cell configeWithModel:self.product shopTitle:self.shopTitle];
    }else {
        [cell configeWithModel:dic[@"model"]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section == _datasource.count - 1 && self.payType != BDProductPayTypePost)||(self.payType == BDProductPayTypePost && indexPath.section == 2)) {
        if (indexPath.row != self.payStyle) {
            self.payStyle = indexPath.row;
            [self requestDatsource];
            [self.tableView reloadData];
        }
    }else {
        NSDictionary *dic = self.datasource[indexPath.section][indexPath.row];
        if ([dic[@"identifier"] isEqualToString:@"redEnvelopeCell"]) {
            BDRedWhiteViewController *vc = [[BDRedWhiteViewController alloc] init];
            vc.datasource = self.redEnvelopeArray;
            vc.chooseFinishedBlock = ^(id redEnvelope){
                self.currentRedEnvelope = redEnvelope;
                [self requestDatsource];
                [self.tableView reloadData];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([dic[@"identifier"] isEqualToString:@"mallAddressCell"]) {
            BDAddressViewController *addressChooseVC = [[BDAddressViewController alloc] init];
            addressChooseVC.chooseAddressBlock = ^(BDUserAddressModel *address) {
                self.address = address;
                [self requestDatsource];
                [self.tableView reloadData];
            };
            addressChooseVC.titleString = ASLocalizedString(@"选择收货地址");
            [self.navigationController pushViewController:addressChooseVC animated:YES];
        }
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        UITableViewController* tvc=[[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
        [self addChildViewController:tvc];
        [tvc.view setFrame:CGRectMake(0, 64, kBDScreenWidth, kBDScreenHeight - 64)];
        self.tableView = tvc.tableView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[BDCouponPayTableViewCell class] forCellReuseIdentifier:@"couponPayCell"];
        [_tableView registerClass:[BDPayDefaultTableViewCell class] forCellReuseIdentifier:@"defaultCell"];
        [_tableView registerClass:[BDPayRedEnvelopeTableViewCell class] forCellReuseIdentifier:@"redEnvelopeCell"];
        [_tableView registerClass:[BDPayStyleTableViewCell class] forCellReuseIdentifier:@"payStyleCell"];
        [_tableView registerClass:[BDMalAddressTableViewCell class] forCellReuseIdentifier:@"mallAddressCell"];
        [_tableView registerClass:[BDMallProductPayTableViewCell class] forCellReuseIdentifier:@"mallProductPayCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [self customFooterView];
        if (self.payType == BDProductPayTypeTopUp) {
            _tableView.tableHeaderView = [self customTopUpView];
        }
        _tableView.separatorInset = UIEdgeInsetsZero;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)customTopUpView{
    UIView *backgroundView = [[UIView alloc] init];
    backgroundView.top = 10 + 64;
    backgroundView.left = 0;
    backgroundView.width = kBDScreenWidth;
    backgroundView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backgroundView];
    
    UILabel *rechargeMoneyLabel = [[UILabel alloc] init];
    rechargeMoneyLabel.top = 15;
    rechargeMoneyLabel.left = 15;
    rechargeMoneyLabel.text = ASLocalizedString(@"充值金额");
    rechargeMoneyLabel.textColor = [UIColor colorWithHexString:@"1c1c1c"];
    rechargeMoneyLabel.font = [UIFont systemFontOfSize:15];
    [rechargeMoneyLabel sizeToFit];
    [backgroundView addSubview:rechargeMoneyLabel];
    
    UILabel *RMBLabel = [[UILabel alloc] init];
    RMBLabel.top = rechargeMoneyLabel.bottom + 20;
    RMBLabel.left = 15;
    RMBLabel.text = @"¥";
    RMBLabel.textColor = [UIColor colorWithHexString:@"1c1c1c"];
    RMBLabel.font = [UIFont systemFontOfSize:25];
    [RMBLabel sizeToFit];
    [backgroundView addSubview:RMBLabel];
    
    UITextField *textField = [[UITextField alloc] init];
    textField.left = RMBLabel.right + 15;
    textField.top = rechargeMoneyLabel.bottom + 20;
    textField.size = CGSizeMake(kBDScreenWidth - 15 - textField.left, RMBLabel.height);
    textField.placeholder = ASLocalizedString(@"请输入充值金额");
    textField.font = [UIFont systemFontOfSize:25];
    textField.textColor = [UIColor colorWithHexString:@"1c1c1c"];
    textField.clearButtonMode = UITextFieldViewModeAlways;
    textField.borderStyle = UITextBorderStyleNone;
    [backgroundView addSubview:textField];
    
    
    UIView *lineView = [[UIView alloc] init];
    lineView.top = textField.bottom + 20;
    lineView.left = 15;
    lineView.size = CGSizeMake(kBDScreenWidth  - 30, 1);
    lineView.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    [backgroundView addSubview:lineView];
    backgroundView.height = lineView.bottom + 20;
    
    return backgroundView;
}

- (UIView *)customFooterView{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
    
    self.payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _payButton.size = CGSizeMake(kBDScreenWidth - 20, 40);
    _payButton.centerX = kBDScreenWidth / 2.0;
    _payButton.top = 20;
    _payButton.backgroundColor = [UIColor colorWithHexString:@"#4d7aad"];
    [_payButton setTitle:ASLocalizedString(@"确认支付")forState:UIControlStateNormal];
    [_payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [[_payButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        self.notification = @"1";
        if (self.payType == BDProductPayTypeTopUp) {
            if (self.payStyle == BDPayViewControllerPayStyleWeixin) {
               // [self wxPayWithPara:para];
            }else if (self.payStyle == BDPayViewControllerPayStyleZhifubao) {
               // [self aliPayWithPara:para];
            }
            return;
        }
        if (self.payType == BDProductPayTypeProduct) {
            if (self.address == nil) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"请选择收货地址")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
                return;
            }
        }
        
        if (self.payType == BDProductPayTypePost && self.currentRedEnvelope != nil) {
            //这里调用红包购买帖子的接口
            [MBManager showLoadingAlert:ASLocalizedString(@"正在购买")clickHidden:NO clickBlock:nil];
            NSString *url = [NSString stringWithFormat:@"%@post/%@/buy/hongBao", KBDBaseURL, self.productId];
            NSString *headValid = [BDUserModel getHeaderValidation];
            
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
            [signal subscribeNext:^(id  _Nullable x) {
                [MBManager hideAlert];
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.successedBlock) {
                        self.successedBlock();
                    }
                }];
            }];
            
            [signal subscribeError:^(NSError * _Nullable error) {
                [MBManager hideAlert];
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买失败")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }];
            return;
        }
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.payResultBlock = ^(int state) {
            if (state == 1) {
                [self adjustControllers];
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.successedBlock) {
                        self.successedBlock();
                    }
                }];
            }else if (state == 2) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }else if (state == 3) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }
        };
        
        NSString *typeString = [NSString stringWithFormat:@"%@", @(self.payType)];
        if (self.payType == BDProductPayTypeVIP) {
            typeString = @"2";
        }
        
        NSMutableDictionary *para = @{@"id":self.productId,
                                      @"type":typeString}.mutableCopy;
        
        if (self.payType == BDProductPayTypeProduct) {
            [para setObject:@(self.address.address_id) forKey:@"address_id"];
        }else if (self.payType == BDProductPayTypeCoupon) {
            if (self.currentRedEnvelope != nil) {
                [para setObject:@(self.currentRedEnvelope.my_id) forKey:@"hong_bao_id"];
            }
        }else if (self.payType == BDProductPayTypeTransferToShop) {
            [para setObject:[NSString stringWithFormat:@"%@", self.price] forKey:@"transfer_amount"];
        }
        
        if (self.payStyle == BDPayViewControllerPayStyleBalance) {
            DNPayAlertView *payAlert = [[DNPayAlertView alloc]init];
            payAlert.detail = ASLocalizedString(@"支付");
            payAlert.amount = [self.price floatValue];
            [payAlert show];
            payAlert.completeHandle = ^(NSString *inputPwd) {
                [para setObject:inputPwd forKey:@"password"];
                [MBManager showLoadingAlert:@"" clickHidden:NO clickBlock:nil];
                self.notification = @"2";
                self.paraDic = para.mutableCopy;
            };
            payAlert.returnButtonAction = ^(){
                BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
                forgetVC.type = ASLocalizedString(@"支付密码");
                [self.navigationController pushViewController:forgetVC animated:YES];
            };
            
        }else if (self.payStyle == BDPayViewControllerPayStyleWeixin) {
            [self wxPayWithPara:para];
        }else if (self.payStyle == BDPayViewControllerPayStyleZhifubao) {
            [self aliPayWithPara:para];
        }
    }];
    _payButton.layer.masksToBounds = YES;
    _payButton.layer.cornerRadius = 4;
    [footerView addSubview:_payButton];
    
    footerView.height = _payButton.bottom + 10;
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;//6222600750008040410
}

-(void)balanceWithPata:(NSDictionary *)para{
    NSString *url = [NSString stringWithFormat:@"%@payment/balance", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
        if (self.successedBlock) {
            self.successedBlock();
        }
        NSString *url = [NSString stringWithFormat:@"%@users/%@?need_manager=1", KBDBaseURL, @([BDUserModel getCurrentUser].user_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
            [newUser saveCurrentUser];
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        errorCode = error.code;
        switch (error.code) {
            case 40004:{
                [MBManager hideAlert];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"注意")message:ASLocalizedString(@"您的余额不足，请更换支付方式")delegate:self
                                                      cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
                alert.tag = 100;
                [alert show];
            }break;
            case 40105:{
                [MBManager hideAlert];
                [self firstInterface];
            }break;
            case 40107:{
                [MBManager hideAlert];
                [self firstInterface];
            }break;
            case 40106:{
                [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"未设置支付密码，请前往个人设置页面设置支付密码")clickHidden:NO clickBlock:nil];
            }break;
            default:
                break;
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
}

- (void)aliPayWithPara:(NSDictionary *)para{
    
    NSString *url = [NSString stringWithFormat:@"%@payment/ali/orderInfo", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        NSString *appScheme = @"beBoyAliPay";
        [[AlipaySDK defaultService] payOrder:x[@"info"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
            if (stateCode == 9000) {
                [self adjustControllers];
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.successedBlock) {
                        self.successedBlock();
                    }
                }];
            }else if (stateCode == 4000) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }else if (stateCode == 6001) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"支付宝请求数据错误：%@"), error);
    }];
}


- (void)wxPayWithPara:(NSDictionary *)para{
    
    NSString *url = [NSString stringWithFormat:@"%@payment/wechat/preOrder", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        PayReq *request = [[PayReq alloc] init];
        request.openID = x[@"app_id"];
        request.partnerId = x[@"merchant_id"];
        request.prepayId = x[@"prepay_id"];
        request.package = @"Sign=WXPay";
        request.nonceStr= x[@"nonce_str"];
        request.timeStamp= (UInt32)[x[@"timestamp"] integerValue];
        request.sign= x[@"sign"];
        [WXApi sendReq:request];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"微信统一下单错误：%@"), error);
    }];
}

- (void)adjustControllers{
    NSMutableArray *controllers = self.navigationController.viewControllers.mutableCopy;
    for (int i = 0; i < controllers.count; i++) {
        UIViewController *controller = controllers[i];
        if ([NSStringFromClass(controller.class) isEqualToString:@"BDScanViewController"] || [NSStringFromClass(controller.class) isEqualToString:@"BDShopPayViewController"]) {
            [controllers removeObject:controller];
            i--;
        }
    }
    self.navigationController.viewControllers = controllers;
}

-(void)firstInterface{
    errorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight)];
    errorView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.5];
    [[[[UIApplication sharedApplication] delegate] window] addSubview:errorView];
    
    UIView *errorBackView = [[UIView alloc] init];
    errorBackView.left = 40;
    errorBackView.size = CGSizeMake(kBDScreenWidth - 80, 150);
    errorBackView.top = (kBDScreenHeight - 150) / 2;
    errorBackView.backgroundColor = [UIColor whiteColor];
    [errorView addSubview:errorBackView];
    
    UILabel *reminderLabel = [[UILabel alloc] init];
    reminderLabel.left = 25;
    reminderLabel.top = 50;
    reminderLabel.width = errorBackView.width - 50;
    if (errorCode == 40105) {
        reminderLabel.text = ASLocalizedString(@"支付密码错误，请重试");
    }else if (errorCode == 40107){
        reminderLabel.text = ASLocalizedString(@"你输入的密码已经错误3次了，请重置密码");
    }
    reminderLabel.numberOfLines = 0;
    reminderLabel.textColor = [UIColor colorWithHexString:@"333333"];
    reminderLabel.font = [UIFont systemFontOfSize:15];
    reminderLabel.height = [reminderLabel.text heightForFont:[UIFont systemFontOfSize:15] width:reminderLabel.width];
    [errorBackView addSubview:reminderLabel];
    
    UIButton *forgetPassButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (errorCode == 40105) {
        [forgetPassButton setTitle:ASLocalizedString(@"忘记密码")forState:UIControlStateNormal];
    }else if (errorCode == 40107){
        [forgetPassButton setTitle:ASLocalizedString(@"重置密码")forState:UIControlStateNormal];
    }
    forgetPassButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [forgetPassButton setTitleColor:[UIColor colorWithHexString:@"48a2d6"] forState:UIControlStateNormal];
    [forgetPassButton sizeToFit];
    forgetPassButton.bottom = errorBackView.height - 25;
    forgetPassButton.right = errorBackView.width - 25;
    [errorBackView addSubview:forgetPassButton];
    [[forgetPassButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
        forgetVC.type = ASLocalizedString(@"支付密码");
        [self.navigationController pushViewController:forgetVC animated:YES];
    }];
    
    UIButton *tryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tryButton setTitle:ASLocalizedString(@"重试")forState:UIControlStateNormal];
    tryButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [tryButton setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
    [tryButton sizeToFit];
    tryButton.right = forgetPassButton.left - 25;
    tryButton.bottom = forgetPassButton.bottom;
    [errorBackView addSubview:tryButton];
    if (errorCode == 40105) {
        tryButton.hidden = NO;
    }else if (errorCode == 40107){
        tryButton.hidden = YES;
    }
    [[tryButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        errorView.hidden = YES;
        [_payButton sendActionsForControlEvents:UIControlEventTouchUpInside];
    }];
}


-(void)KeyboardWillShowNotification{
    self.notification = @"1";
}

-(void)KeyboardDidHideNotification{
    if ([self.notification isEqualToString:@"2"]) {
        [self balanceWithPata:self.paraDic];
        self.notification = @"1";
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillShowNotification) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardDidHideNotification) name:UIKeyboardDidHideNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (errorView) {
        [errorView removeFromSuperview];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
